package com.jeesite.modules.general.utils;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.idgen.IdGen;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 *腾讯云（COS）对象存储
 * @author jeffery
 *  */
public class CosApiUtils {

    // 存储桶名称
    private static final String bucketName = "hui-de-bao-1358866491";
    //secretId 秘钥id
    private static final String SecretId = "AKIDlU1LSS3SedPyjT02rSqCNLGzZzGLEuV6";
    //SecretKey 秘钥
    private static final String SecretKey = "50iQvCG6jLo480f7LzUm15wa2HOL7h4F";
    // COS 区域 购买时选择的区域
    private static final String regionId = "ap-chengdu";
    // 访问域名
    public static final String URL = "https://hui-de-bao-1358866491.cos.ap-chengdu.myqcloud.com/";
    // 创建COS 凭证
    private static COSCredentials credentials = new BasicCOSCredentials(SecretId,SecretKey);
    // 配置 COS 区域 就购买时选择的区域
    private static ClientConfig clientConfig = new ClientConfig(new Region(regionId));

    /**
     * 上传腾讯云（COS）文件
     * @param file 上传的文件 prefix保存的文件地址，一般设定后不要更改
     */
    public static JSONObject uploadFile(MultipartFile file, String fileName, String prefix){
        JSONObject object = new JSONObject();
        object.put("result",true);
        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials,clientConfig);
        String filePath = file.getOriginalFilename();
        try {
            String substring = filePath.substring(filePath.lastIndexOf("."));
            File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()),substring);
            file.transferTo(localFile);
            if ("".equals(fileName)) {
                fileName = IdGen.nextId() + substring;
            }
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName,prefix+"/"+fileName,localFile);
            cosClient.putObject(objectRequest);
            object.put("result",false);
            object.put("filePath",URL+prefix+"/"+fileName);
            object.put("fileName",fileName);
            object.put("fileName2",prefix+"/"+fileName);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            cosClient.shutdown();
        }
        return object;
    }
    /**
     * 删除对象存储指定文件
     * @param key 指定要删除的键  prefix指定删除的文件夹名
     */
    public static boolean delCOSFile(String key,String prefix){
        boolean result = false;
        if(!"".equals(key) && key!=null){
            // 多个数据进行删除，传入key值
            String[] keys = key.split(",");
            // 初始化用户身份信息(secretId, secretKey)
            COSCredentials cred = new BasicCOSCredentials(SecretId, SecretKey);
            ClientConfig clientConfig = new ClientConfig(new Region(regionId));
            // 生成cos客户端
            COSClient cosClient = new COSClient(cred, clientConfig);
            try {
                for(int i=0;i<keys.length;i++){
                    cosClient.deleteObject(bucketName, prefix+"/"+keys[i]);
                }
                result = true;
            } catch (Throwable tb) {
                result = false;
                tb.printStackTrace();
            }
            // 关闭客户端
            cosClient.shutdown();
        }
        return result;
    }
}
